import { ElMessageBox, ElMessage } from 'element-plus'
import { h } from 'vue'

/**
 * 删除确认弹窗 Hook
 * @param {Object} options 配置项
 * @returns {Object} 删除确认相关方法
 */
export const useDeleteConfirm = (options = {}) => {
  const defaultOptions = {
    title: '系统提示',
    message: '确定要删除选中的数据吗？',
    subMessage: '此操作不可逆，请谨慎操作！',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    showInput: false,
    inputPlaceholder: '请输入确认文本',
    dangerouslyUseHTMLString: false,
    ...options,
  }

  /**
   * 显示删除确认弹窗
   * @param {Function} deleteFunction 删除操作函数
   * @param {Object} customOptions 自定义配置
   * @returns {Promise}
   */
  const showDeleteConfirm = async (deleteFunction, customOptions = {}) => {
    const finalOptions = { ...defaultOptions, ...customOptions }

    // 构建消息内容
    const content = h('div', { style: 'line-height: 1.6; text-align: left;' }, [
      h(
        'p',
        {
          style: 'margin: 0 0 8px 0; font-size: 16px; font-weight: 500; color: #303133;',
        },
        finalOptions.message
      ),
      finalOptions.subMessage
        ? h(
            'p',
            {
              style: 'margin: 0; color: #909399; font-size: 14px;',
            },
            finalOptions.subMessage
          )
        : null,
    ])

    try {
      await ElMessageBox.confirm(content, finalOptions.title, {
        confirmButtonText: finalOptions.confirmButtonText,
        cancelButtonText: finalOptions.cancelButtonText,
        type: finalOptions.type,
        showInput: finalOptions.showInput,
        inputPattern: finalOptions.inputPattern,
        inputPlaceholder: finalOptions.inputPlaceholder,
        inputErrorMessage: finalOptions.inputErrorMessage,
        dangerouslyUseHTMLString: finalOptions.dangerouslyUseHTMLString,
        customClass: 'delete-confirm-dialog',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm' && finalOptions.showInput) {
            if (finalOptions.confirmText && instance.inputValue !== finalOptions.confirmText) {
              ElMessage.error(finalOptions.inputErrorMessage || '输入内容不正确')
              return
            }
          }
          done()
        },
      })

      // 确认后执行删除操作
      if (deleteFunction && typeof deleteFunction === 'function') {
        await deleteFunction()
      }

      return Promise.resolve()
    } catch (error) {
      // 用户取消或出错
      return Promise.reject(error)
    }
  }

  /**
   * 单条删除确认
   * @param {Function} deleteFunction 删除函数
   * @param {String} itemName 删除项名称
   * @param {Object} customOptions 自定义选项
   */
  const confirmDeleteSingle = (deleteFunction, itemName = '这条数据', customOptions = {}) => {
    return showDeleteConfirm(deleteFunction, {
      message: `确定删除${itemName}吗？`,
      subMessage: '删除后将无法恢复，请谨慎操作！',
      ...customOptions,
    })
  }

  /**
   * 批量删除确认
   * @param {Function} deleteFunction 删除函数
   * @param {Number|Array} count 删除数量或选中的数据
   * @param {Object} customOptions 自定义选项
   */
  const confirmDeleteBatch = (deleteFunction, count = 0, customOptions = {}) => {
    const deleteCount = Array.isArray(count) ? count.length : count

    if (deleteCount === 0) {
      ElMessage.warning('请先选择要删除的数据')
      return Promise.reject(new Error('未选择数据'))
    }

    return showDeleteConfirm(deleteFunction, {
      message: `确定要删除选中的 ${deleteCount} 条数据吗？`,
      subMessage: '批量删除操作不可逆，请谨慎操作！',
      ...customOptions,
    })
  }

  /**
   * 危险删除确认（需要输入确认文本）
   * @param {Function} deleteFunction 删除函数
   * @param {String} confirmText 需要输入的确认文本
   * @param {Object} customOptions 自定义选项
   */
  const confirmDeleteDangerous = (deleteFunction, confirmText = 'DELETE', customOptions = {}) => {
    return showDeleteConfirm(deleteFunction, {
      title: '危险操作确认',
      message: '这是一个危险操作！',
      subMessage: `为了确保安全，请输入 "${confirmText}" 来确定删除`,
      confirmButtonText: '执行危险操作',
      showInput: true,
      confirmText,
      inputPlaceholder: `请输入 ${confirmText}`,
      inputErrorMessage: `请输入正确的确认文本：${confirmText}`,
      ...customOptions,
    })
  }

  return {
    showDeleteConfirm,
    confirmDeleteSingle,
    confirmDeleteBatch,
    confirmDeleteDangerous,
  }
}

/**
 * 快速删除确认方法（无需实例化）
 */
export const deleteConfirm = {
  /**
   * 基础删除确认
   */
  async basic(deleteFunction, message = '确定要删除这条数据吗？') {
    const { showDeleteConfirm } = useDeleteConfirm()
    return showDeleteConfirm(deleteFunction, { message })
  },

  /**
   * 批量删除确认
   */
  async batch(deleteFunction, count) {
    const { confirmDeleteBatch } = useDeleteConfirm()
    return confirmDeleteBatch(deleteFunction, count)
  },

  /**
   * 单条删除确认
   */
  async single(deleteFunction, itemName) {
    const { confirmDeleteSingle } = useDeleteConfirm()
    return confirmDeleteSingle(deleteFunction, itemName)
  },

  /**
   * 危险删除确认
   */
  async dangerous(deleteFunction, confirmText = 'DELETE') {
    const { confirmDeleteDangerous } = useDeleteConfirm()
    return confirmDeleteDangerous(deleteFunction, confirmText)
  },

  /**
   * 自定义删除确认
   */
  async custom(deleteFunction, options) {
    const { showDeleteConfirm } = useDeleteConfirm(options)
    return showDeleteConfirm(deleteFunction)
  },
}
